package com.power.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.power.domain.SysUser;
import com.power.domain.SysUserRole;
import com.power.domain.dto.SysUserDto;
import com.power.mapper.SysUserMapper;
import com.power.mapper.SysUserRoleMapper;
import com.power.service.SysUserRoleService;
import com.power.service.SysUserService;
import com.power.util.AuthUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private  SysUserMapper mapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Override
    public Page pagelist(Page<SysUser> page, String name) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(name))
        {
            wrapper.like(SysUser::getUsername,name);
        }
        page = this.page(page,wrapper);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOne(SysUserDto sysUserDto) {
         if(sysUserDto==null)
            {
            return false;
         }
        SysUser sysUser1=new SysUser();
            //为空的话是一个新增业务
            BeanUtils.copyProperties(sysUserDto,sysUser1);
            sysUser1.setPassword(passwordEncoder.encode(sysUserDto.getPassword()));
            sysUser1.setCreateUserId(AuthUtils.getLoginUserId());
            boolean save = this.save(sysUser1);
            if (save)
            {
                List<Long> roleIdList = sysUser1.getRoleIdList();
                if (roleIdList!=null&&roleIdList.size()>0) {
                    List<SysUserRole> sysUserRoles = new ArrayList<>();
                    roleIdList.forEach(roleId->{
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setRoleId(roleId);
                        sysUserRole.setUserId(sysUser1.getUserId());
                        sysUserRoles.add(sysUserRole);
                    });
                    return sysUserRoleService.saveBatch(sysUserRoles);
                }
            }
            return save;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int usdateOne(SysUserDto sysUserDto) {

        if (sysUserDto==null)
        {
            return 0;
        }
        //1.先删除角色关联表
        sysUserRoleService.deleteByUserIdOne(sysUserDto.getUserId());
        SysUser sysUser1=new SysUser();
        BeanUtils.copyProperties(sysUserDto,sysUser1);
        sysUser1.setPassword(passwordEncoder.encode(sysUserDto.getPassword()));
        //更新用户信息
        int i = mapper.updateById(sysUser1);
        //更新成功后添加新的用户角色关系表
        if (i>0)
        {
            List<SysUserRole> sysUserRoles = new ArrayList<>();
            List<Long> roleIdList = sysUser1.getRoleIdList();
            if (roleIdList!=null&&roleIdList.size()>0)
            {
                for (Long roleIdLists : roleIdList) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser1.getUserId());
                    sysUserRole.setRoleId(roleIdLists);
                    sysUserRoles.add(sysUserRole);
                }
                boolean b = sysUserRoleService.saveBatch(sysUserRoles);

            }

        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByLsitID(String id) {
        if (!StringUtils.hasText(id))
        {
            return 0;
        }
        String[] split = id.split(",");
        List<Long> collect = Arrays.stream(split)
                .map(String::trim) // 去除每个字符串的前后空白
                .map(s -> {
                    try {
                        return Long.parseLong(s);
                    } catch (NumberFormatException e) {
                        System.err.println("无效的数字格式: " + s);
                        return null; // 处理异常的返回值为 null
                    }
                })
                .filter(v -> v != null) // 过滤掉无效的值（null）
                .collect(Collectors.toList()); // 收集为 List

        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysUser::getUserId,collect);
//        int i = mapper.deleteBatchIds(id);
        int i = mapper.delete(wrapper);
        if (i>0)
        {
            sysUserRoleService.deleteByUserId(collect);
        }
        return i;
    }

    /**
     * 点击编辑是根据id获取需要修改的用户的信息，和权限关联表的信息
     * @param id
     * @return
     */
    @Override
    public SysUser getByIdandRoleList(Long id) {
        SysUser byId = this.getById(id);
        if (byId!=null)
        {
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, id));
            if (sysUserRoles!=null&&sysUserRoles.size()>0)
            {
                List<Long> collect = sysUserRoles.stream().map(sysUserRole -> sysUserRole.getRoleId()).collect(Collectors.toList());
                if (collect!=null&&collect.size()>0)
                {
                    byId.setRoleIdList(collect);
                }

            }
        }
        return byId;
    }

}
